import {
	defineStore
} from 'pinia'
import {
	loginApi,
	userInfoApi,
	logoutApi,
} from '@/api/auth.js'
import {
	store
} from '@/stores/index.js'

const LOCAL_KEY_TOKEN = 'token'
const LOCAL_KEY_USER_INFO = 'userInfo'

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			token: uni.getStorageSync(LOCAL_KEY_TOKEN),
			userInfo: uni.getStorageSync(LOCAL_KEY_USER_INFO),
			merchantInfo: null,
			investCode: null
		}
	},
	getters: {
		isLogin: (state) => {
			return !!(state.token && state.userInfo && state.userInfo.id)
		},
		isOwn: (state) => {
			return !!(state.userInfo && state.userInfo.ownState === 2);
		}
	},
	actions: {
		setInestCode(value) {
			this.investCode = value
		},
		setMerchantInfo(value) {
			this.merchantInfo = value
		},
		setToken(value) {
			this.token = value
			uni.setStorageSync(LOCAL_KEY_TOKEN, value)
		},
		async login(data) {
			const res = await loginApi(data)
			if (res.token) {
				this.token = res.token
				uni.setStorageSync(LOCAL_KEY_TOKEN, res.token)
			}
			return res
		},
		async getUserInfo() {
			const res = await userInfoApi()
			if (res) {
				this.userInfo = res
				uni.setStorageSync(LOCAL_KEY_USER_INFO, res)
			}
		},
		async logout() {
			const res = await logoutApi()
			console.log('退出', res)
			uni.setStorageSync(LOCAL_KEY_USER_INFO, null)
			setToken(null)
			uni.navigateTo({
				url: '/pages/login/login'
			})
		},
	}
})

export const useUserStoreWithOut = () => {
	return useUserStore(store)
}